package com.atguigu.gulimall.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;

import javax.validation.Valid;


/**
 * 商品三级分类
 *
 * @author leifengyang
 * @email leifengyang@gmail.com
 * @date 2019-10-01 22:50:32
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redisson;
    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     * redis缓存数据
     */
    @RequestMapping("/list/tree")
    public R list(){
       String categoryListJson = stringRedisTemplate.opsForValue().get("categoryList");
        if(StringUtils.isEmpty(categoryListJson)) {
            List<CategoryEntity> entities = categoryService.listWithTree();
            String jsonString = JSON.toJSONString(entities);
            stringRedisTemplate.opsForValue().set("categoryList", jsonString);
            return R.ok().put("data", jsonString);
        }else {
            return R.ok().put("data", categoryListJson);
        }
    }
    /**
     * 信息
     * 分布式锁
     */
    @RequestMapping("/info/{catId}")
    //@RequiresPermissions("product:category:info")
    public R info(@PathVariable("catId") Long catId){
        CategoryEntity category = null;
        RLock lock = redisson.getLock("Category_info_catId");
        lock.lock();
        try {
            System.out.println("lock"+Thread.currentThread().getName());
            Thread.sleep(30000);
            category = categoryService.getById(catId);
        }catch (Exception e){
            e.getMessage();
        }finally {
            lock.unlock();
            System.out.println("unlock"+Thread.currentThread().getName());
        }
        return R.ok().put("data", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:category:save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);

        return R.ok();
    }

    @RequestMapping("/update/sort")
    //@RequiresPermissions("product:category:update")
    public R updateSort(@RequestBody CategoryEntity[] category){
        categoryService.updateBatchById(Arrays.asList(category));
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:category:update")
    public R update(@RequestBody CategoryEntity category){

		categoryService.updateCascade(category);
        return R.ok();
    }


    /**
     * 删除
     * @RequestBody:获取请求体，必须发送POST请求
     * SpringMVC自动将请求体的数据（json），转为对应的对象
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("product:category:delete")
    public R delete(@RequestBody Long[] catIds){


		//categoryService.removeByIds(Arrays.asList(catIds));

        categoryService.removeMenuByIds(Arrays.asList(catIds));

        return R.ok();
    }
    @GetMapping("writeLock")
    @ResponseBody
    //读锁
    public String writeLock(){
        RReadWriteLock writeLock = redisson.getReadWriteLock("ReadWriteLock");
        RLock lock = writeLock.writeLock();
        try {
            lock.lock();
            Thread.sleep(3000);
            return "WriteLock"+Thread.currentThread();
        }catch (Exception e) {
            e.getMessage();
        }finally {
            lock.unlock();
        }
        return "write-null"+Thread.currentThread();
    }

    @GetMapping("readLock")
    public String readLock(){
        RReadWriteLock writeLock = redisson.getReadWriteLock("ReadWriteLock");
        RLock lock = writeLock.readLock();
        try {
            lock.lock();
            return "ReadLock"+Thread.currentThread();
        }catch (Exception e){
            e.getMessage();
        }finally {
            lock.unlock();
        }
        return "read-lock"+Thread.currentThread();
    }
}
